import 'dart:async';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import '../../../../../lib_runtime/logger.dart';
import 'room_music_center_controller.dart';

/// 在线音乐列表
class RoomMusicListController extends GetxController {
  late RoomMusicCenterController centerController;

  final MusicChartInfo chartInfo;

  int page = 1;
  List<Music>? data;
  StreamSubscription? subscription;

  RoomMusicListController(this.chartInfo);
  RefreshController controller = RefreshController(initialRefresh: false);
  bool canLoadMore = false;
  @override
  void onInit() {
    super.onInit();
    centerController = Get.find<RoomMusicCenterController>();
  }

  @override
  void onReady() {
    super.onReady();
    refreshData();
  }

  @override
  void onClose() {
    subscription?.cancel();
    super.onClose();
  }

  refreshData() async {
    page = 1;
    loadData();
  }

  loadData() async {
    RLog.d('musicLoadData:${chartInfo.id}');
    subscription?.cancel();
    String requestId =
        await centerController.loadMusicList(chartInfo.id ?? 0, page: page);
    subscription =
        centerController.subscribeMusicCollection(requestId).listen((event) {
      MusicCollection collection = event.result;
      RLog.d(
          'musicLoadData:${chartInfo.id} page:${collection.getPage()} count:${collection.getCount()} total:${collection.getTotal()}');
      if (page == 1) {
        data = [];
      }
      if (collection.getCount() > 0) {
        for (int i = 0; i < collection.getCount(); i++) {
          data?.add(collection.getMusic(i));
        }
        page++;
      }
      canLoadMore = data!.length < collection.getTotal();
      controller.refreshCompleted();
      if (page == 1) {
        controller.refreshCompleted();
      } else {
        controller.loadComplete();
      }
      update();
    });
  }

  int get count => data?.length ?? 0;

  void playAll() async {
    if (data != null && count > 0) {
      centerController.playlist = data!;
      Music first = data!.first;
      MediaPlayerState state = await centerController.playState(first);
      if (state != MediaPlayerState.playerStatePlaying) {
        centerController.play(data!.first);
      }
    }
  }
}
